package com.m3839.sdk.pay.task;

import com.m3839.sdk.common.core.ApiError;
import com.m3839.sdk.common.core.Constant;
import com.m3839.sdk.common.event.SubjectBus;

import java.util.Observable;
import java.util.Observer;

/**
 * @author ChenBaoyang
 * @description: PayOrderHeartTask
 * @date 2021/12/9 16:26
 */
public class PayOrderPollingTask extends IPollingTask{

    private PayTask payTask;

    /** 订单ID */
    private String orderId;

    public PayOrderPollingTask(PayTask payTask, String orderId){
        this.payTask = payTask;
        this.orderId = orderId;
    }

    @Override
    protected void doWork() {
        SubjectBus.get().observe(Constant.HYKB_EVENT_PAY_ORDER_QUERY, new Observer() {
            @Override
            public void update(Observable o, Object arg) {
                ApiError apiError = (ApiError) arg;
                int code = apiError.code;
                if (code == Constant.HYKB_CODE_ORDER_NOT_FIND && betweenPollStage()) {
                    // 继续轮询
                    handler.sendEmptyMessageDelayed(MSG_POLLING, POLLING_INTERVAL);
                } else {
                    // 次数置为最大，介绍轮询，相应订单结果给玩家
                    count = POLLING_MAX_TIME;
                    isRunning = false;
                    // 这边将支付成功的code强制转为9000
                    payTask.handPayCallBack(code == Constant.HYKB_CODE_SUCCESS ? 9000 : code, apiError.message);
                }
            }
        });
        payTask.getPayModel().orderQuery(orderId);
    }


}
